# Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd.
# SPDX-License-Identifier: MulanPSL-2.0

import os
import logging

from collections import defaultdict

from agent.common.config import Config
from agent.domain.base import BaseDomain
from agent.common.system import sysCommand

logger = logging.getLogger('common')

class MySQL(BaseDomain):
    __domain__ = "my_cnf"
    
    def __init__(self):
        super().__init__(domain_name = self.__domain__)
        self.mycnf_path  = "/etc/my.cnf"
        self.backup_file = os.path.join(Config.BACKUP_PATH, "my.cnf")
        if not os.path.exists(self.mycnf_path):
            raise Exception("Can not find config file: file /etc/my.cnf do not exists!")

    def get_value(self, param_name):
        if param_name in ["core-file", "skip_ssl", "skip_name_resolve"]:
            return sysCommand("cat /etc/my.cnf  |grep -w {name} | tail -n1 |wc -L |awk '{{if (sum=$(wc -L \"{name}\") && $0==$sum) print \"SET_TRUE\";else print \"SET_FALSE\"}}'".format(name = param_name.strip()))
        else:
            return sysCommand("cat /etc/my.cnf |grep -w {name} | tail -n1 | awk -F'=' '{{print$2}}'".format(name = param_name.strip()))

    def set_value(self, param_name, param_value):
        if param_name in ["core-file", "skip_ssl", "skip_name_resolve"] and param_value == "SET_TRUE":
            sysCommand("echo {name} >> /etc/my.cnf".format(name=param_name.strip()))
        else:
            sysCommand("echo {name}={value} >> /etc/my.cnf".format(name=param_name.strip(), value=param_value))

    def pre_setting(self):
        with open(self.mycnf_path, "w") as f:
            f.write("[client-server]\n!includedir /etc/my.cnf.d\n[mysqld]\n")

    def backup(self, param_list):
        backup_result = defaultdict(dict)
        for param_name in param_list.keys():
            try:
                value = self.get_value(param_name = param_name)
                backup_result[param_name] = {"suc": True, "msg": value}
            except Exception as e:
                backup_result[param_name] = {"suc": False, "msg": "{}".format(e)}
                logger.error("'{}:{}' reading error: {}".format(self.domain_name, param_name, e))
                continue
        if os.path.exists(self.backup_file):
            return backup_result
        sysCommand("echo y | cp {} {}".format(self.mycnf_path, self.backup_file))
        return backup_result

    def rollback(self):
        if not os.path.exists(self.backup_file):
            return
        sysCommand("echo y | cp {} {}".format(self.backup_file, self.mycnf_path))
        os.remove(self.backup_file)